//
//  HomeSearchVC.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/11/17.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "HomeSearchVC.h"
#import "HomeSearch_NavBar.h"
#import "HomeSearchModel.h"
#import "HomeSearchFrame.h"
#import "HomeSearchCell.h"
#import "HomeSearchSectionView.h"
//#import "MyShipmentDetailVC.h"
//#import "MyCollectDetailVC.h"

@interface HomeSearchVC () <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) HomeSearch_NavBar *navBar;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *historyArray;

@end

@implementation HomeSearchVC

-(NSMutableArray *)historyArray {
    if (!_historyArray) {
        _historyArray = [NSMutableArray array];
    }
    return _historyArray;
}

-(HomeSearch_NavBar *)navBar {
    if (!_navBar) {
        _navBar = [[HomeSearch_NavBar alloc] initWithFrame:CGRectMake(0, 0, ScreenW, NaviHeight)];
        __weak_self;
        _navBar.backBlock = ^{
            [weakself.rt_navigationController popViewControllerAnimated:YES];
        };
        _navBar.searchBlock = ^(NSString * _Nonnull text) {
            [weakself requestForSearch:text];
            [weakself saveHistory:text];
        };
    }
    return _navBar;
}

- (void)requestForSearch:(NSString *)text {
//    [HttpRequest PostWithApi:ReceiptDeliveryHomeSearch params:@{@"wa_num":text} progress:^(NSProgress * _Nonnull progress) {
//
//    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
//        if (code) {
//            if ([responseObject[@"type"] intValue] == 1) {
//                MyShipmentDetailVC *vc = [MyShipmentDetailVC new];
//                vc.wa_id = responseObject[@"wa_id"];
//                [self.rt_navigationController pushViewController:vc animated:YES];
//            }else {
//                MyCollectDetailVC *vc = [MyCollectDetailVC new];
//                vc.wa_id = responseObject[@"wa_id"];
//                [self.rt_navigationController pushViewController:vc animated:YES];
//            }
//        }
//    } fail:^(NSError * _Nonnull error) {
//
//    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    [self.view addSubview:self.navBar];
    self.view.backgroundColor = [UIColor whiteColor];
    [self configCollectionView];
    [self configHistoryArray];
}

- (void)saveHistory:(NSString *)text {
    NSMutableArray *localArr = [USER_D objectForKey:@"Local_Search_Keyword"];
    NSMutableArray *mut = [NSMutableArray arrayWithArray:localArr];
    if ([mut containsObject:text]) {
        [mut removeObject:text];
    }
    [mut insertObject:text atIndex:0];
    localArr = mut;
    while (localArr.count > 10) {
        [localArr removeLastObject];
    }
    [USER_D setObject:localArr forKey:@"Local_Search_Keyword"];
    [USER_D synchronize];
    [self configHistoryArray];
}

- (void)deleteHistory:(NSInteger)idx {
    [self.historyArray removeObjectAtIndex:idx];
    NSMutableArray *localArr = [USER_D objectForKey:@"Local_Search_Keyword"];
    NSMutableArray *mut = [NSMutableArray arrayWithArray:localArr];
    if (mut.count) {
        [mut removeObjectAtIndex:idx];
    }
    localArr = mut;
    while (localArr.count > 10) {
        [localArr removeLastObject];
    }
    [USER_D setObject:localArr forKey:@"Local_Search_Keyword"];
    [USER_D synchronize];
    [self configHistoryArray];
}

- (void)configHistoryArray {
    NSMutableArray *localArr = [USER_D objectForKey:@"Local_Search_Keyword"];
    NSMutableArray *mut = [NSMutableArray array];
    [localArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        HomeSearchModel *historyModel = [HomeSearchModel new];
        historyModel.wordText = obj;
        HomeSearchFrame *historyFrame = [HomeSearchFrame new];
        historyFrame.wordModel = historyModel;
        [mut addObject:historyFrame];
    }];
    self.historyArray = mut;
    [self.collectionView reloadData];
    [USER_D synchronize];
}

- (void)configCollectionView {
//    self.automaticallyAdjustsScrollViewInsets = NO;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.navBar.nim_bottom, ScreenW, ScreenH - NaviHeight - BottomHeight) collectionViewLayout:[[CommonSearchVCCollectionLayout alloc] init]];
    self.collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[HomeSearchCell class] forCellWithReuseIdentifier:HomeSearchCellID];
    [self.collectionView registerClass:[HomeSearchSectionView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HomeSearchSectionViewID];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.historyArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeSearchCell *cell = [HomeSearchCell HomeSearchCellWithReuseIdentifier:HomeSearchCellID forIndexPath:indexPath withCollectionView:collectionView];
    HomeSearchFrame *frame = self.historyArray[indexPath.row];
    cell.frameModel = frame;
    __weak_self;
    cell.deleteBlock = ^{
        [weakself deleteHistory:indexPath.row];
    };
    cell.wordBlock = ^(NSString * _Nonnull text) {
        weakself.navBar.fieldText = text;
        [weakself requestForSearch:text];
    };
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeSearchFrame *frame = self.historyArray[indexPath.row];
    return frame.size;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        HomeSearchSectionView *headView = [HomeSearchSectionView HomeSearchSectionViewWithViewOfKind:kind atIndexPath:indexPath withIdentifier:HomeSearchSectionViewID withCollectionView:collectionView];
        headView.titleStr = @"历史搜索";
        return headView;
    }
    return [UICollectionReusableView new];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    HomeSearchSectionView *headView = [[HomeSearchSectionView alloc] init];
    return headView.size;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeMake(0, 0);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

@end

@implementation CommonSearchVCCollectionLayout

- (instancetype)init {
    if (self = [super init]) {
        
    }
    return self;
}

- (void)prepareLayout {
    [super prepareLayout];
    self.minimumInteritemSpacing = 10;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
    // 获取所有元素，如有header 或者footer 也会包括
    NSMutableArray* attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
    self.resoultDic = [[NSMutableDictionary alloc]init];
    // 设置cell 等间距，根据需求可以修改
    NSInteger maximumSpacing = 10;
    for (int i = 0; i < [attributes count]; i++) {
        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
        // 排除 header footer
        if (currentLayoutAttributes.representedElementKind != nil) {
            continue;
        }
        // 获取 每个cell 的 y 值， 将所有的具有相同 y值的cell 加入数组 组合成 Key- Value
        NSString *currentWidth = [NSString stringWithFormat:@"%f",currentLayoutAttributes.frame.origin.y];
        if (![self.resoultDic.allKeys containsObject:currentWidth]) {
            NSMutableArray *dataArray = [[NSMutableArray alloc]init];
            [self.resoultDic setObject:dataArray forKey:currentWidth];
        }
        NSMutableArray *array = self.resoultDic[currentWidth];
        [array addObject:currentLayoutAttributes];
    }
    // 取出每一行cells，将第一个cell 的x 改变
    for (int i = 0; i < self.resoultDic.allKeys.count; i++) {
        NSString *key = self.resoultDic.allKeys[i];
        NSArray *valueArray = self.resoultDic[key];
        for (int j = 0; j < valueArray.count; j++) {
            UICollectionViewLayoutAttributes *JLayoutAttributes = valueArray[j];
            if (j == 0 ) {
                CGRect frame = JLayoutAttributes.frame;
                frame.origin.x = 20;//  修改成你想要的 值
                JLayoutAttributes.frame = frame;
            }else{
                UICollectionViewLayoutAttributes *prevLayoutAttributes = valueArray[j - 1];
                // 当cell 的个数大于2个的时候
                NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
                CGRect frame = JLayoutAttributes.frame;
                frame.origin.x = origin + maximumSpacing;
                JLayoutAttributes.frame = frame;
            }
        }
    }
    return attributes;
}

@end
